/* eslint-disable */
import axios from "axios";
import qs from "qs";
import { ElMessage } from "element-plus"
import Router from '../../router/index'
// 创建axios实例
const service = axios.create({
    baseURL: "/api",
    timeout: 60000, // 请求超时时间
    withCredentials: true,
});
// request拦截器
service.interceptors.request.use(
    async config => {
        config.headers.post["Content-Type"] =
            "application/x-www-form-urlencoded;charset=UTF-8";
        // if (config.method === "post") {
        //     config.data = qs.stringify(config.data);
        // }
        config = Object.assign(config, config.config)
        return config;
    },
    error => {
        Promise.resolve(error);
    }
);

// respone拦截器
service.interceptors.response.use(
    response => {
        let data = response.data;
        if (data.code == 200) {

        } else if (data.code == 403) {
            ElMessage.error({ duration: 1500, message: "登录过期或没有权限" });
            Router.push({ path: "/" });
        } else if (data.code == 5011) {
            ElMessage.error({ duration: 1500, message: "登录过期或账号在其他地方登录" });
            Router.push({ path: "/" });
        } else {
            ElMessage.error({ duration: 1500, message: data.message });
        }
        return response;

    },
    error => {
        const { response } = error
        if (response.status === 403) {
            ElMessage.error({ duration: 1500, message: "登录过期或没有权限" });
            Router.push({ path: "/" });
        } else {
            ElMessage({
                message: "服务器错误，请稍后再试",
                type: "error"
            });
        }

        return Promise.reject(error);
    }
);
export function requestData(params, httpMethod, path, config, success_callback) {
    let key = 'data';
    httpMethod = httpMethod.toUpperCase();
    if (httpMethod === 'GET') {
        key = 'params';
    }
    return new Promise((resolve, reject) => {
        service({
            url: path,
            method: httpMethod,
            [key]: params,
            config
        }).then(
            response => {
                if (response.config.config) {
                    resolve(response);

                } else {
                    resolve(response.data);

                }
                success_callback && success_callback(response.data);
            }

        )
    });
}
export function upload(url, data) {
    return new Promise((resolve, reject) => {
        service
            .post(url, data)
            .then(
                response => {
                    resolve(response);
                },
                err => {
                    reject(err);
                }
            )
            .catch(res => {
                console.log("请求超时", res);
            });
    });
}